from django.shortcuts import render, redirect
from models_user.models import Url
from models_goods.models import Duty
from django.http import HttpResponse
from ribbon.views import permission
from random import choice


img_url_list = ['237072833.jpeg', '237072834.jpeg', '21783476.jpeg', '237072843.jpeg', '237072847.jpeg',
                '237072829.jpeg', '237072832.jpeg']


@permission
def management(request):
    context = {'urls': Url.objects.all().values_list(),
               'dutys': Duty.objects.all().values_list(),
               'img_url': 'http://pic.qqoi.cn/img_bizhi/{}'.format(choice(img_url_list))}
    if request.method == 'GET':
        pass
    elif request.method == 'POST':
        url_id = request.POST['url_id']
        duty_list = request.POST.getlist('dutys')
        url = Url.objects.get(pk=url_id)
        if url:
            url.duty.clear()
            url.duty.add(*duty_list)
            context['mes'] = '修改成功'
        else:
            context['mes'] = '数据异常'
    else:
        return HttpResponse('数据异常')
    return render(request, 'management/management.html', context)


@permission
def add_url(request):
    if request.method == 'POST':
        Url.objects.create(url=request.POST['url_value'])
        return redirect('authorityManagement:management')
    else:
        return HttpResponse('数据异常')




